<template>
	<view class="product-content">
		<scroll-view scroll-y class="scroll">
			<view class="tabs">
				<view class="tab-item text-overflow-hidden-1" :class="{'active-tab': tab.gid === params.classify_gid}"
					v-for="(tab, index) in classifyList" :key="tab.gid" @click="changeTab(tab)">
					{{ tab.title }}
				</view>
			</view>
		</scroll-view>
		<scroll-view scroll-y class="scroll-lists" @scrolltolower="scrolltolower">
			<view class="lists">
				<view class="list-item-wrap" :class="{'active': ids.includes(item)}" v-for="(item, index) in lists"
					:key="index" @click="handleCheck(item)">
					<!-- <view class="">
						<view class="iconfont icon-check"></view>
					</view> -->
					<view class="list-item">
						<view class="item-img">
							<image :src="item.thumb" mode="widthFix"></image>
						</view>
						<view class="flex flex-column justify-between flex-1">
							<view class="">
								<view class="title">{{item.title}}</view>
								<view v-if="item.desc" class="explain text-overflow-hidden-1">{{item.desc}}</view>
							</view>
							<view class="flex align-center justify-between flex-1 padding-t12">
								<view class="price">
									<text class="price-symbol">¥</text>
									<text class="price-num">{{item.selling_price | formatPrice($formatPrice, '')}}</text>
									<text class="price-unit" style="color: black;padding-left: 4rpx;">元</text>
									<!-- <text class="price-unit" style="color: black;padding-left: 4rpx;">起</text>
									<text class="price-unit">/天租价</text> -->
								</view>
								<view class="item-select-btn" v-if="item.relation && item.relation.length" @click="selectItem(item)">选择</view>
								<com-input-number v-else :value="item.number" :show-minus="false" @input="changeItemNumber($event, item)"></com-input-number>
								<!-- <view v-if="index === 0" class="item-tag new-tag">新品</view>
								<view v-if="index === 5" class="item-tag hot-tag">热租</view> -->
							</view>
						</view>
					</view>
				</view>
				
				<view v-if="lists.length === 0" class="empty"> 暂无数据 </view>
			</view>
		</scroll-view>


		<view class="footer-btns">
			<view class="foot-price flex align-center justify-between">
				<view class="cart" @click="openCart">
					<view class="count">{{totalCount}}</view>
					<view class="iconfont icon-cart"></view>
					<view class="">购物车</view>
				</view>
				<view class="">
					<view class="flex align-center ">
						<view class="total">
							<text class="total-title">合计</text>
							<text>(含运费)：</text>
						</view>
						<view class="total-price">
							<text class="price-unit">￥</text>
							<text>{{totalPrice | formatPrice($formatPrice, '')}}</text>
						</view>
					</view>
					<!-- <view class="flex align-center ">
						<view class="preferential">
							<text>免运费</text>
							<text>(优惠)：</text>
						</view>
						<view class="preferential">
							<text class="price-unit">¥</text>
							<text>30</text>
						</view>
					</view> -->
				</view>
			</view>
			<view class="btns">
				<!-- <button class="cancel" @click="back">上一步</button> -->
				<!-- <button v-if="difference > 0" class="confirm disabled">还差{{ difference }}元方可下单</button> -->
				<button class="confirm-btn flex-1" @click="next">确认提交</button>
			</view>
		</view>
		
		<!-- 规格 -->
		<specs-popup ref="specs" @confirm="confirmSpecs" @cancel="cancelSpecs"></specs-popup>
		<!-- 购物车列表 -->
		<cart-list ref="cart" @change="getCartList" @changeLoading="changeLoading"></cart-list>
	</view>
</template>

<script>
	import SpecsPopup from '../../components/specs-popup.vue';
	import CartList from '../../components/cart-list.vue';
	import formatPrice from '@/mixins/formatPrice.js';
	
	export default {
		name: "product-list",
		components: { SpecsPopup, CartList },
		mixins:[formatPrice],
		data() {
			return {
				classifyList: [],
				ids: [],
				lists: [],
				params: {
					page: 1, // 页码 必需 示例值: 1
					limit: 10, // 页数 必需 示例值: 10
					classify_gid: '', // 分类 
					brand_gid: '', // 品牌 可选
					key: '', // 搜索：名称/标题/条形码
				},
				more: true, // 是否有更多数据
				loading:  false, // 加载中
				
				cartList: [], // 购物车列表
				totalCount: 0, // 总数量
				totalPrice: 0, // 总价格
				difference: 0, // 差价
				
				timer: null, // 修改数量的定时器
				timer2: null, // 提交的定时
				preItem: {}, // 上一个修改的item
			}
		},
		onShow() {
			this.getCartList()
			this.getList()
		},
		onReady() {
			this.getClassifyList()
			this.getList()
		},
		methods: {
			// 打开购物车
			openCart() {
				this.$refs.cart.open(this.cartList)
			},
			selectItem(item) {
				this.$refs.specs.open(item)
			},
			confirmSpecs(item, value) {
				this.getCartList()
				// item.number++
			},
			cancelSpecs(item) {
				// const index = this.lists.findIndex(el=> el.gid === item.gid)
				// this.lists[index].number = 0
				// this.$forceUpdate()
			},
			changeItemNumber(value, item) {
				// 1. 判断购物车中是否有该产品
				const prod = this.cartList.find(el=> el.product_gid === item.gid)
				if (item.gid === this.preItem.gid) {
					clearTimeout(this.timer)
				}
				this.preItem = item
				this.loading = true
				this.timer = setTimeout(()=> {
					if (prod) {
						// 更新数量
						if (value) {
							this.handleUpdateCart(prod.gid, value)
						} else {
							this.handleDeleteCart(prod.gid)
						}
					} else {
						// 添加产品到购物车
						this.addToCart(value, item)
					}
				}, 300)
			},
			// 更新购物车数量
			handleUpdateCart(gid, quantity) {
				this.loading = true
				this.$api.agentProductEditApi(gid, {quantity}, {loading:false}).then(res=> {
					this.getCartList()
				}).catch(err=> {
					console.log('err', err);
				}).finally(()=> {
					this.loading = false
				})
			},
			// 删除购物车
			handleDeleteCart(gid) {
				this.loading = true
				this.$api.agentProductDeleteApi(gid, {}, {loading:false}).then(res=> {
						this.getCartList()
				}).catch(err=> {
					console.log('err', err);
				}).finally(()=> {
					this.loading = false
				})
			},
			// 添加到购物车
			addToCart(value, item) {
				const params = {
					product_gid: item.gid,
					quantity: value,
					item_product_gid: '',
					issave: 1
				}
				const data = this.cartList.find(el=> el.gid === item.gid)
				if (data) {
					params.quantity = value - data.quantity
				}
				this.loading = true
				this.$api.agentProductAddApi(params).then(res=> {
					this.getCartList()
				}).catch(err=> {
					console.log('err', err);
				}).finally(()=> {
					this.loading = false
				})
			},
			scrolltolower() {
				if (this.more) {
					this.params.page++
					this.getList()
				}
			},
			getClassifyList() {
				const params = {
					limit: 9999, //页数 必需 示例值: 10
					page: 1, //页码 必需 示例值: 1
					belong_module: 'product_classify', //模块类型 必需 示例值: product_classify
					belong_id: '', //模块id 可选
					pid: '', //可选 父级ID，传0值显示顶级数据
				}
				this.$api.classifyListApi(params).then(res=> {
					this.classifyList = res.data
					this.classifyList.unshift({
						gid: '',
						title: '全部'
					})
					this.params.classify_gid = res.data[0].gid
				}).catch(err=> {
					console.log('err', err)
				})
			},
			getList() {
				this.loading = true
				this.$api.agentProductListApi(this.params).then(res=> {
					if (this.params.page === 1) {
						this.lists = []
					}
					
					if (res.data.length === 0 || res.data.length < this.params.limit) {
						this.more = false
					} else {
						this.more = true
					}
					
					const oldList = [...this.lists]
					this.lists = oldList.concat(res.data.map(item=> ({...item, number: 0})))
					this.initNumber()
				}).catch(err=> {
					console.log('err', err);
				}).finally(()=> {
					this.loading = false
				})
			},
			// 获取购物车列表
			getCartList() {
				this.$api.agentCartListApi({}, {loading: false}).then(res=> {
					this.totalCount = res.data.reduce((sum, item) => sum + item.quantity, 0);
					this.totalPrice = res.data.reduce((sum, item) => sum + item.total_price, 0);
					this.difference = 10000 - Number(this.totalPrice)
					this.cartList = res.data
					this.$refs.cart.getList(this.cartList)
					
					this.initNumber()
				}).catch(err=> {
					console.log('err', err);
				})
			},
			changeLoading(loading) {
				this.loading = loading
			},
			initNumber() {
				if (this.cartList.length && this.lists.length) {
					this.lists.forEach(item=> {
						const data = this.cartList.find(el=> el.product_gid === item.gid)
						if (data) {
							item.number = data.quantity
						} else {
							item.number = 0
						}
					})
				}
			},
			back() {
				this.$emit('back')
			},
			next() {
				if (!this.loading) {
					this.handleSubmit()
				} else {
					uni.showLoading({ mask: true })
					clearInterval(this.timer2)
					this.timer2 = setInterval(()=> {
						if (!this.loading) {
							clearInterval(this.timer2)
							this.handleSubmit()
							uni.hideLoading()
						}
					}, 200)
				}
			},
			handleSubmit() {
				if (this.cartList && this.cartList.length) {
					const cartIds = this.cartList.map(item=> item.gid).join(',')
					uni.navigateTo({
						url: '/pages/agent/procure/submit/submit?cartIds='+cartIds
					})
					this.$refs.cart.close()
				} else {
					uni.showToast({
						icon: 'none',
						title: '请选择产品'
					})
				}
			},
			changeTab(tab) {
				this.params.page = 1
				this.params.classify_gid = tab.gid
				this.getList()
			},
			// 前往商品详情
			handleCheck(item) {
				if (this.ids.includes(item)) {
					this.ids = this.ids.filter(id => id !== item)
				} else {
					this.ids.push(item)
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.product-content {
		display: flex;
		flex: 1;
		height: 100%;
		overflow: hidden;
	}

	.scroll {
		width: 220rpx;
		height: 100%;
		box-sizing: border-box;
		background-color: #FAFAFA;
	}

	.tabs {
		box-sizing: border-box;
		padding-bottom: calc(300rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		padding-bottom: calc(300rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/

		.tab-item {
			padding: 32rpx 26rpx;
			box-sizing: border-box;
			position: relative;

			font-size: 28rpx;
			font-weight: 400;
			line-height: 40rpx;
			text-align: left;

			&:after {
				content: '';
				position: absolute;
				left: 10%;
				bottom: 0;
				width: 78%;
				height: 1px;
				background-color: #F1F1F1;
			}
			
		}

		.active-tab {
			font-weight: 700;
			background-color: #FFFFFF;

			&:after {
				background-color: #FFFFFF;
			}
		}
	}


	.scroll-lists {
		flex: 1;
		width: 100%;
		height: 100%;
		box-sizing: border-box;
		background-color: #FFFFFF;
	}

	.lists {
		box-sizing: border-box;
		padding-bottom: calc(300rpx+ constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
		padding-bottom: calc(300rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/

		.list-item-wrap {
			display: flex;
			align-items: center;
			// padding-left: 16rpx;

			.icon-check {
				font-size: 34rpx;
				color: #C3C2CD;
			}
		}

		.active {
			.icon-check {
				font-size: 34rpx;
				color: #000000;
			}
		}

		.list-item {
			position: relative;
			display: flex;
			width: 100%;
			padding: 32rpx;
			box-sizing: border-box;

			&:after {
				content: '';
				position: absolute;
				left: 32rpx;
				bottom: 0;
				width: calc(100% - 64rpx);
				height: 1px;
				background-color: #F1F1F1;
			}

			.item-img {
				width: 164rpx;
				height: 164rpx;
				display: flex;
				flex-shrink: 0;
				margin-right: 38rpx;
				align-items: center;
				justify-content: center;
				border-radius: 12rpx;
				background-color: #F6F6F6;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.title {
				font-size: 34rpx;
				font-weight: 400;
				line-height: 46rpx;
				text-align: left;
			}

			.explain {
				max-width: 282rpx;
				color: #999999;
				font-size: 20rpx;
				font-weight: 400;
				line-height: 28rpx;
				text-align: left;
				padding-top: 8rpx;
			}
			
			.item-select-btn {
				color: #FFFFFF;
				font-size: 18rpx;
				font-weight: 400;
				line-height: 24rpx;
				padding: 4rpx 20rpx;
				border-radius: 999px;
				background: var(--gradient-color-vertical);
			}
			
			.price {
				display: flex;
				align-items: flex-end;
			}

			.price-symbol {
				font-size: 22rpx;
				font-weight: 600;
				line-height: 32rpx;
				text-align: left;
			}

			.price-num {
				font-size: 28rpx;
				font-weight: 700;
				line-height: 32rpx;
				text-align: left;
			}

			.price-unit {
				font-size: 14rpx;
				font-weight: 600;
				line-height: 24rpx;
				text-align: left;
				color: rgba(0, 0, 0, 0.5);
			}

			.item-tag {
				color: #FFFFFF;
				font-size: 18rpx;
				font-weight: 400;
				line-height: 24rpx;
				padding: 4rpx 20rpx;
				border-radius: 999px;
			}

			.new-tag {
				background-color: #FF0000;
			}

			.hot-tag {
				background-color: #FF6B00;
			}

		}
	}


	.all-check {
		display: flex;
		align-items: center;
		font-size: 28rpx;
		font-weight: 600;
		line-height: 38rpx;
		text-align: left;
		color: #000000;

		.icon-check {
			color: #C3C2CD;
			font-size: 34rpx;
			padding-right: 16rpx;
		}
	}

	.all-check-active {
		
		.icon-check {
			color: #000000;
		}
	}

	.footer-btns {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		width: 100%;
		z-index: 99999;
		box-sizing: border-box;
		background-color: #FFFFFF;
		box-shadow: 0px 0px 33rpx rgba(0, 0, 0, 0.05);

		.foot-price {
			padding: 24rpx 42rpx;
			
			.cart {
				position: relative;
				font-size: 20rpx;
				font-weight: 400;
				line-height: 28rpx;
				text-align: left;
				color: #000000;
				padding: 0 16rpx;
				
				.icon-cart {
					width: 56rpx;
					height: 56rpx;
					
					font-size: 56rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
				
				.count {
					position: absolute;
					top: 0;
					right: 0;
					min-width: 36rpx;
					height: 36rpx;
					font-size: 20rpx;
					font-weight: 400;
					line-height: 28rpx;
					color: #FFFFFF;
					padding: 0 8rpx;
					box-sizing: border-box;
					background-color: #E64A19;
					border-radius: 999px;
					transform: translateY(-25%) translateX(15%);
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.total {
				font-size: 20rpx;
				font-weight: 400;
				line-height: 28rpx;
				text-align: left;
				color: rgba(0, 0, 0, 0.4);
			}

			.total-title {
				font-size: 28rpx;
				font-weight: 400;
				line-height: 38rpx;
				text-align: left;
				color: #000000;
			}

			.total-price {
				font-size: 34rpx;
				font-weight: 700;
				line-height: 38rpx;
				text-align: left;
				color: #FF754C;
			}

			.price-unit {
				font-size: 20rpx;
				font-weight: 400;
				line-height: 28rpx;
				text-align: left;
			}

			.preferential {
				font-size: 28rpx;
				font-weight: 400;
				line-height: 38rpx;
				text-align: left;
				color: rgba(0, 0, 0, 0.4);
			}

			.detial-btn {
				font-size: 28rpx;
				font-weight: 700;
				line-height: 38rpx;
				text-align: left;
				color: #FF754C;
				display: flex;
				align-items: center;
				padding-left: 12rpx;
			}

			.icon-arrow {
				margin-left: 8rpx;
				transform: rotate(90deg);
			}

			.icon-arrow-right {
				font-size: 16rpx;
			}
		}

		.btns {
			gap: 14rpx;
			display: flex;
			align-items: center;
			padding: 20rpx 32rpx;
			padding-bottom: calc(20rpx + constant(safe-area-inset-bottom)); ///兼容 IOS<11.2/
			padding-bottom: calc(20rpx + env(safe-area-inset-bottom)); ///兼容 IOS>11.2/
		}

		.cancel {
			width: 178rpx;
			height: 82rpx;
			border: 1px solid var(--primary-color);

			color: var(--primary-color);
			font-size: 34rpx;
			font-weight: 400;
			line-height: 82rpx;
			text-align: center;
		}

		.confirm {
			flex: 1;
			height: 82rpx;
			font-size: 34rpx;
			font-weight: 400;
			line-height: 82rpx;
			text-align: center;
			color: #FFFFFF;
		}
	}
</style>